package com.helloandroid.ads

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import com.helloandroid.tools.AppConfig
import com.helloandroid.tools.MyLog

object ResumeAdUtil {
    var pausedActivityName = ""
    var resumedActivityName = ""

    fun registResumeAd(app:Application){
        // 用于播放广告
        app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                MyLog.info("onActivityCreated action:${activity.javaClass.name}")
            }

            override fun onActivityStarted(activity: Activity) {
            }

            override fun onActivityResumed(activity: Activity) {
                MyLog.info("onActivityResumed action:${activity.javaClass.name}")
                resumedActivityName = activity.javaClass.name
                if (!VideoAdUtil.playing &&
                        resumedActivityName == pausedActivityName &&
                        pausedActivityName != "com.helloandroid.ads.StartAdActivity" &&
                        pausedActivityName != "com.helloandroid.WelcomeActivity" &&
                        AppConfig.AdToggle && !AppConfig.isFake) {
                    // 播放广告
                    val intent = Intent(activity, StartAdActivity::class.java)
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    app.startActivity(intent)
                }
            }

            override fun onActivityPaused(activity: Activity) {
                MyLog.info("onActivityPaused action:${activity.javaClass.name}")
                pausedActivityName = activity.javaClass.name
            }

            override fun onActivityStopped(activity: Activity) {
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
            }

            override fun onActivityDestroyed(activity: Activity) {
                MyLog.info("onActivityDestroyed action:${activity.javaClass.name}")
            }
        })
    }
}